package cn.jantd.modules.activiti.controller;

import cn.jantd.core.annotation.AutoLog;
import cn.jantd.core.api.vo.Result;
import cn.jantd.core.system.query.QueryGenerator;
import cn.jantd.core.system.vo.LoginUser;
import cn.jantd.modules.activiti.command.BackSingleTaskCmd;
import cn.jantd.modules.activiti.command.PreviousTask;
import cn.jantd.modules.activiti.command.RejectToAnyWhereTaskCmd;
import cn.jantd.modules.activiti.entity.*;
import cn.jantd.modules.activiti.entity.TaskOpinion;
import cn.jantd.modules.activiti.entity.Task;
import cn.jantd.modules.activiti.command.BackTaskCmd;
import cn.jantd.modules.activiti.extract.CommonUtil;
import cn.jantd.modules.activiti.extract.EntityWrapper;
import cn.jantd.modules.activiti.service.*;
import cn.jantd.modules.activiti.service.impl.*;
import cn.jantd.modules.activiti.util.Base64Utils;
import cn.jantd.modules.system.entity.*;
import cn.jantd.modules.system.service.ISysRoleTeamuserService;
import cn.jantd.modules.system.service.ISysTeamUserService;
import cn.jantd.modules.system.service.ISysUserRoleService;
import cn.jantd.modules.system.service.ISysUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.ActivityProcessor;
import org.activiti.engine.*;
import org.activiti.engine.history.*;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.ServiceImpl;
import org.activiti.engine.impl.TaskServiceImpl;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandExecutor;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.ReadOnlyProcessDefinition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ExecutionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.HMProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/act/task/")
public class TaskController {

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Autowired
    ISysUserRoleService roleUserService;

    @Autowired
    IProcessService processService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    ITaskFileTypeService iTaskFileTypeService;

    @Autowired
    IdentitylinkService identitylinkService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysTeamUserService teamUserService;
    @Autowired
    ISysRoleTeamuserService roleTeamuserService;

    @Autowired
    ProcessCustomService processCustomService;

    @Autowired
    ActRuExecutionServiceImpl actRuExecutionService;

    @Autowired
    IRunTaskService runTaskService;

    @Autowired
    ActHIDetailService actHIDetailService;

    @Autowired
    IActHiTaskinstService iActHiTaskinstService;
    /*  public List<String> roleIdList(LoginUser user) {
          SysUserRole entity = new SysUserRole();
          //先取到当前登录用户的id
          entity.setUserId(user.getId());
          List<SysUserRole> userRoles = roleUserService.list(EntityWrapper.wrapper(entity));
          List<String> roleIdList = new ArrayList<String>();
          for (SysUserRole each : userRoles) {
              roleIdList.add(each.getRoleId());
          }
          return roleIdList;
      }*/
    static List<org.activiti.engine.task.Task> backIds;

    public List<String> roleIdList(LoginUser user) {

        SysTeamUser user1 = new SysTeamUser();
        //先取到当前登录用户的id
        user1.setUserId(user.getId());
        //根据当前用户的id获取到所有的列表信息
/*      String teamid=teamUserService.getById(user.getId()).getTeamId();
      System.out.println("teamid:"+teamid);*/
        /*   entity.setTeamId(teamid);*/
        //根据用户的id查找到这个list数据
        List<SysTeamUser> teamUsersList = teamUserService.list(EntityWrapper.wrapper(user1));

        System.out.println("teamUsersList:" + teamUsersList);
        List<String> roleIdList = new ArrayList<String>();
        for (SysTeamUser each : teamUsersList) {
            SysRoleTeamuser entity = new SysRoleTeamuser();
            List<SysRoleTeamuser> userteam = roleTeamuserService.getByTeamId(each.getTeamId());
            for (SysRoleTeamuser rnn : userteam) {
                entity.setTeamroleId(rnn.getTeamroleId());
                System.out.println("getTeamroleId:" + entity.getTeamroleId());

            }
            roleIdList.add(entity.getTeamroleId());
            System.out.println("roleIdlist:" + roleIdList);
        }
        return roleIdList;
    }

    /**
     * 我的任务
     */
    @ResponseBody
    @GetMapping(value = "mine")
    public Object mineList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, Task task) {
        LoginUser user = CommonUtil.getUser();
        List<org.activiti.engine.task.Task> candidateList = taskService.createTaskQuery().taskCandidateUser(user.getId()).orderByTaskCreateTime().desc().list();
        List<org.activiti.engine.task.Task> playerList = taskService.createTaskQuery().taskCandidateUser(user.getUsername()).orderByTaskCreateTime().desc().list();
        List<org.activiti.engine.task.Task> assigneeList = taskService.createTaskQuery().taskAssignee(user.getId()).orderByTaskCreateTime().desc().list();
        List<org.activiti.engine.task.Task> candidateGroup = taskService.createTaskQuery().taskCandidateGroupIn(roleIdList(user)).orderByTaskCreateTime().desc().list();
        List<org.activiti.engine.task.Task> teamList = taskService.createTaskQuery().taskAssignee(user.getUsername()).orderByTaskCreateTime().desc().list();
        List<org.activiti.engine.task.Task> tasks = new ArrayList<>();
        tasks.addAll(candidateList);
        tasks.addAll(assigneeList);
        tasks.addAll(candidateGroup);
        tasks.addAll(teamList);
        tasks.addAll(playerList);
        List<Task> taskList = new ArrayList<>();

//        Map<String, Map<String, Object>> taskMap = new HashMap<>();
        Set<String> taskSet = new HashSet<String>();
        for (org.activiti.engine.task.Task eachTask : tasks) {
            String taskId = eachTask.getId();
            if (taskSet.contains(taskId)) {
                continue;
            }
            Task taskEntity = new Task(eachTask);
            Map<String, Object> variables = taskService.getVariables(taskId);
            ProcessInfo process = (ProcessInfo) variables.get(ProcessInfo.variables_process_info);
            if (null != process) {
                taskEntity.setUserName(process.getUserName());
                taskEntity.setRemark(process.getRemark());
                taskEntity.setName(process.getModelName());
            }
            taskList.add(taskEntity);
            //如果是自己
//            Map<String, Object> extendMap = new HashMap<>();
//            if (user.getId().equals(startTask.getUserId())) {
//                if (variables.get("flag") != null) {
//                    if (!(boolean) variables.get("flag")) {
//                        extendMap.put("flag", true);
//                    } else {
//                        extendMap.put("flag", false);
//                    }
//                } else {
//                    extendMap.put("flag", true);
//                }
//            } else {
//                extendMap.put("flag", false);
//            }
//            taskMap.put(taskEntity.getId(), extendMap);
            taskSet.add(taskId);
        }
        Result result = new Result();
        result.setResult(new Page().setRecords(taskList).setTotal((long) taskList.size()));
        return result;
    }

    /**
     * 我的处理历史任务
     */
    @ResponseBody
    @GetMapping(value = "mineHistory")
    public Object mineHistory(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, Task task) {
        LoginUser user = CommonUtil.getUser();
        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery().taskVariableValueEquals(ProcessInfo.variables_opinion_user_id, user.getId()).list();
        Result result = new Result();
        result.setResult(new Page().setRecords(taskInstanceList).setTotal((long) taskInstanceList.size()));//todo
        return result;
    }

    @ResponseBody
    @GetMapping("processDetails/{id}")
    public Object processDetails(@PathVariable("id") String taskId) {
        Map<String, Object> variables = taskService.getVariables(taskId);
        Result result = new Result();
        result.setResult(variables.get(ProcessInfo.variables_process_info));
        return result;
    }


    /**
     * 根据 执行对象id获取审批信息
     */
    @ResponseBody
    @GetMapping("getLoadBackButton/{processId}/{taskId}")
    public Object getLoadBackButton(@PathVariable String processId, @PathVariable String taskId) {
        CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
        List previousTaskList = (List) commandExecutor.execute(new PreviousTask(taskId));
        if (((Task) previousTaskList.get(0)).getId().indexOf("StartEvent") != -1) {
            Result result = new Result();
            result.setResult("StartEvent");
            return result;
        }
        Result result = new Result();
        return result;
    }

    /**
     * 根据 执行对象id获取审批信息
     */
    @ResponseBody
    @GetMapping("opinionsByProcessId/{processId}/{taskId}")
    public Object opinionsByProcessId(@PathVariable String processId, @PathVariable String taskId) {
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //保证运行ing
        List<TaskOpinion> leaveList = null;
        if (instance != null) {
            List<org.activiti.engine.task.Task> task = this.taskService.createTaskQuery().processInstanceId(processId).list();
            Map<String, Object> variables = taskService.getVariables(taskId);
            Object o = variables.get(ProcessInfo.variables_opinion_list);
            if (o != null) {
                /*获取历史审核信息*/
                leaveList = (List<TaskOpinion>) o;
            }
        } else {
            leaveList = new ArrayList<>();
            List<HistoricDetail> list = historyService.createHistoricDetailQuery().processInstanceId(processId).list();
            for (HistoricDetail historicDetail : list) {
                HistoricVariableUpdate variable = (HistoricVariableUpdate) historicDetail;
                if (ProcessInfo.variables_opinion_list.equals(variable.getVariableName())) {
                    leaveList.clear();
                    leaveList.addAll((List<TaskOpinion>) variable.getValue());
                }
            }
        }
        Result result = new Result();
        result.setResult(leaveList);
        return result;
    }


    @ResponseBody
    @PostMapping("complete")
    public Result complete(@RequestBody TaskOpinion option) {
        LoginUser user = CommonUtil.getUser();
        option.setFlag(true);
        option.setOpId(user.getId());
        option.setOpName(user.getRealname());
        option.setCreateTime(new Date());

//        保存当前节点文件路径:W

        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(option.getProcessInstanceId()).singleResult();

        QueryWrapper<RunTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper
                .eq("PROC_DEF_ID_", instance.getProcessDefinitionId())
                .eq("ID_", option.getTaskId());
        RunTask runTask = runTaskService.getOne(taskQueryWrapper);
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", runTask.getTaskDefKey());
        TaskFileType taskFileType = new TaskFileType();
        taskFileType.setInstanceId(instance.getId());
        taskFileType.setAttachments(option.getAttachments());
        taskFileType.setAttachmentsName(option.getAttachmentsName());
        iTaskFileTypeService.update(taskFileType, taskFileTypeQueryWrapper);

//        把当前节点保存到流程实例变量中
        this.completeActivityIdLists(instance);

        Map<String, Object> completeVariables = new HashMap<>();
        completeVariables.put(ProcessInfo.variables_flag, option.isFlag());
        //判断节点是否已经拒绝过一次了
        Map<String, Object> variables = taskService.getVariables(option.getTaskId());
        Object isEnd = variables.get(ProcessInfo.variables_need_end);
        if (isEnd != null && (boolean) isEnd && (!option.isFlag())) {
            completeVariables.put(ProcessInfo.variables_need_finish, -1); //结束
        } else {
            if (option.isFlag()) {
                completeVariables.put(ProcessInfo.variables_need_finish, 1);//通过下一个节点
            } else {
                completeVariables.put(ProcessInfo.variables_need_finish, 0);//不通过
            }
        }
        //审批信息叠加
        Object o = variables.get(ProcessInfo.variables_opinion_list);
        List<TaskOpinion> optionList = o == null ? new ArrayList<>() : (List<TaskOpinion>) o;
        optionList.add(option);
        completeVariables.put(ProcessInfo.variables_opinion_list, optionList);
        completeVariables.put(ProcessInfo.variables_opinion_user_id, user.getId());
        // 执行转向任务
        actHIDetailService.deleteAll();
        taskService.complete(option.getTaskId(), completeVariables);
        Result result = new Result();
        result.setResult(option.isFlag());
        return result;
    }


    /**
     * 通过id删除任务
     *
     * @param id
     * @return
     */
    @ResponseBody
    @DeleteMapping(value = "delete")
    public Result<ProcessInfo> delete(@RequestParam(name = "id", required = true) String id) {
        Result<ProcessInfo> result = new Result<>();

        ProcessInfo processInfo = processService.getById(id);
        if (processInfo == null) {
            result.error500("未找到对应实体");
        } else {
            // 当某个用户被删除时,删除其ID下对应的部门数据
            boolean ok = processService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    @ResponseBody
    @PostMapping("back")
    public Result back(@RequestBody TaskOpinion option) {
        LoginUser user = CommonUtil.getUser();
        option.setFlag(false);
        option.setOpId(user.getId());
        option.setOpName(user.getRealname());
        option.setCreateTime(new Date());
        //判断节点是否已经拒绝过一次了
        Map<String, Object> variables = taskService.getVariables(option.getTaskId());
        Object o = variables.get(ProcessInfo.variables_opinion_list);
        List<TaskOpinion> optionList = o == null ? new ArrayList<>() : (List<TaskOpinion>) o;
        optionList.add(option);
        variables.put(ProcessInfo.variables_opinion_list, optionList);
        variables.put(ProcessInfo.variables_opinion_user_id, user.getId());
//        this.backTaskCmd(option.getTaskId(),variables,option.getBackTaskIds());
//        CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
//        commandExecutor.execute(new BackTaskCmd(option.getTaskId(), variables,option.getBackTaskIds()));
//        this.backActivityIdLists(option.getProcessInstanceId());
        try {
//            for(int i = 0;i<option.getBackTaskIds().size();i++){
            if (option.getNodeType().equals("Gateway")) {
                if (option.getBackTaskIds().size() == 1) {
                    boolean b = processCustomService.findBackAvtivity(option.getTaskId());
                    if (b) {
                        QueryWrapper<RunTask> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("ID_", option.getTaskId()).orderByDesc();
                        RunTask runTask = runTaskService.getOne(queryWrapper);
                        QueryWrapper<ActRuExecution> queryExecution = new QueryWrapper<>();
                        queryExecution.eq("ACT_ID_", runTask.getTaskDefKey()).orderByDesc();
                        ActRuExecution actRuExecution = actRuExecutionService.getOne(queryExecution);
                        QueryWrapper<ActRuExecution> query = new QueryWrapper<ActRuExecution>();
                        query.eq("PROC_INST_ID_", actRuExecution.getProcInstId())
                                .eq("IS_CONCURRENT_", actRuExecution.getIsConcurrent()).ne("ACT_ID_", actRuExecution.getActId());
                        List list = actRuExecutionService.list(query);
                        processCustomService.backProcess(option.getTaskId(), option.getBackTaskIds(), variables, option.getTaskInfos());
                        for (int i = 0; i < list.size(); i++) {
                            runTaskService.remove(new QueryWrapper<RunTask>().eq("TASK_DEF_KEY_", ((ActRuExecution) list.get(i)).getActId()));
                        }
                        for (int i = 0; i < list.size(); i++) {
                            actRuExecutionService.remove(new QueryWrapper<ActRuExecution>().eq("ACT_ID_", ((ActRuExecution) list.get(i)).getActId()));
//                            QueryWrapper<TaskFileType> fqueryWrapper = new QueryWrapper<>();
//                            fqueryWrapper.eq("activity_id", ((ActRuExecution) list.get(i)).getActId()).eq("instance_id",((ActRuExecution) list.get(i)).getProcInstId());
//                            iTaskFileTypeService.remove(fqueryWrapper);
                        }
                    }
//                this.rollback(option);
//                processCustomService.backProcess(option.getTaskId(), option.getBackTaskIds(), variables,option.getTaskInfos());
                } else {
                    processCustomService.backProcess(option.getTaskId(), option.getBackTaskIds(), variables, option.getTaskInfos());
                }
            } else if (option.getNodeType().equals("Activity")) {
                CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
                commandExecutor.execute(new BackSingleTaskCmd(option.getTaskId(), variables));
//                QueryWrapper<TaskFileType> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("activity_id", option.getTaskId()).eq("instance_id",option.getProcessInstanceId());
//                iTaskFileTypeService.remove(queryWrapper);
            }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 判断是否是网关
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @ResponseBody
    @PostMapping("isNotGateway")
    public Result isNotGateway(@RequestBody TaskOpinion option) {
        //判断回退节点是否是网关 wb
        List list = this.isGateway(option);
        if (list.get(0) == null) {
//            Result result = new Result<>();
//            QueryWrapper<ActHiTaskinst> queryWrapper = new QueryWrapper<ActHiTaskinst>();
//            queryWrapper.eq("ID_", option.getTaskId());
//            ActHiTaskinst actHiTaskinst = iActHiTaskinstService.getOne(queryWrapper);
//
//            Task task = new Task();
//            task.setId(actHiTaskinst.getTaskDefKey());
//            task.setName(actHiTaskinst.getName());
//            List listTask = new ArrayList<>();
//            listTask.add(task);
            CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
            List previousTaskList = (List) commandExecutor.execute(new PreviousTask(option.getTaskId()));
            Task task = new Task();
//            task.setId(previousTaskList.getTaskDefKey());
//            task.setName(previousTaskList.getName());
            List listTask = new ArrayList<>();
            listTask.add(task);

//            result.setResult(listTask);
            return new Result();
        }
        if (list.size() > 0) {
            if (((Task) list.get(0)).getNodeType().equals("Gateway")) {
                Result result = new Result<>();
                result.setNodeType("Gateway");
                result.setResult(list);
                return result;
            } else if (((Task) list.get(0)).getNodeType().equals("Activity")) {
                Result result = new Result<>();
                result.setNodeType("Activity");
                result.setResult(list);
                return result;
            }
        }
        return new Result();
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 判断回退节点是否为网关
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    public List isGateway(TaskOpinion option) {
        Map<String, Object> variables = taskService.getVariables(option.getTaskId());
        CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
        List list = (List) commandExecutor.execute(new BackTaskCmd(option.getTaskId(), variables, option.getBackTaskIds()));
        return list;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 流程过程图片
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("getShineProcImage/{processInstanceId}")
    @ResponseBody
    public String getShineProcImage(HttpServletRequest request, HttpServletResponse resp, @PathVariable String processInstanceId)
            throws IOException {
        JSONObject result = new JSONObject();
        JSONArray shineProImages = new JSONArray();
        BASE64Encoder encoder = new BASE64Encoder();
        InputStream imageStream = generateStream(request, resp, processInstanceId, true);
        if (imageStream != null) {
            String imageCurrentNode = Base64Utils.ioToBase64(imageStream);
            if (StringUtils.isNotBlank(imageCurrentNode)) {
                shineProImages.add(imageCurrentNode);
            }
        }
        InputStream imageNoCurrentStream = generateStream(request, resp, processInstanceId, false);
        if (imageNoCurrentStream != null) {
            String imageNoCurrentNode = Base64Utils.ioToBase64(imageNoCurrentStream);
            if (StringUtils.isNotBlank(imageNoCurrentNode)) {
                shineProImages.add(imageNoCurrentNode);
            }
        }
        result.put("id", UUID.randomUUID().toString());
        result.put("errorNo", 0);
        result.put("images", shineProImages);
        return result.toJSONString();
    }


    public InputStream generateStream(HttpServletRequest request, HttpServletResponse resp, String processInstanceId, boolean needCurrent) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        HistoricProcessInstance historicProcessInstance =
                historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String processDefinitionId = null;
        List<String> executedActivityIdList = new ArrayList<String>();
        List<String> currentActivityIdList = new ArrayList<>();
        List<HistoricActivityInstance> historicActivityInstanceList = new ArrayList<>();
        if (processInstance != null) {
            processDefinitionId = processInstance.getProcessDefinitionId();
            if (needCurrent) {
                currentActivityIdList = this.runtimeService.getActiveActivityIds(processInstance.getId());
            }
        }
        if (historicProcessInstance != null) {
            processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            historicActivityInstanceList =
                    historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list();
            for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
                executedActivityIdList.add(activityInstance.getActivityId());
            }
        }

        if (StringUtils.isEmpty(processDefinitionId) || executedActivityIdList.isEmpty()) {
            return null;
        }

        //高亮线路id集合
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity, historicActivityInstanceList);

        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        //List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);
        HMProcessDiagramGenerator diagramGenerator = (HMProcessDiagramGenerator) processEngineConfiguration.getProcessDiagramGenerator();
        //List<String> activeIds = this.runtimeService.getActiveActivityIds(processInstance.getId());

        InputStream imageStream = diagramGenerator.generateDiagram(
                bpmnModel, "png",
                executedActivityIdList, highLightedFlows,
                processEngine.getProcessEngineConfiguration().getActivityFontName(),
                processEngine.getProcessEngineConfiguration().getLabelFontName(),
                "宋体",
                null, 1.0, currentActivityIdList);

        return imageStream;
    }

    /**
     * 获取需要高亮的线
     *
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {

        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取上传文件格式
     * @Date: 2020/5/6
     * @Version: 1.0
     */


    @GetMapping("loadTaskFileType/{processId}/{taskId}")
    @ResponseBody
    public Result loadTaskFileType(@PathVariable String processId, @PathVariable String taskId) {

        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        QueryWrapper<RunTask> runTaskQueryWrapper = new QueryWrapper<>();
        runTaskQueryWrapper.eq("ID_", taskId);

        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", runTaskService.getOne(runTaskQueryWrapper).getTaskDefKey())
                .orderByDesc("create_time");

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);

        Result result = new Result();
        result.setResult(taskFileType.getOutputFormat());
        return result;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取节点上传文件
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("getLoadTaskFiles/{processId}/{taskId}")
    @ResponseBody
    public Result getLoadTaskFiles(@PathVariable String processId, @PathVariable String taskId) {

        Map<String, Object> variables = taskService.getVariables(taskId);
        CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
        List previousTaskList = (List) commandExecutor.execute(new PreviousTask(taskId));

//        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        Result result = new Result();
//        String activityId = null;
//        List activityIdLists = (List) runtimeService.getVariable(instance.getId(), "activityIdLists");
//        if (activityIdLists != null && activityIdLists.size() > 0) {
//            activityId = (String) activityIdLists.get(0);
//        }
//        if (activityId == null) {
//            return result;
//        }
        List list = new ArrayList<>();
        for (int i = 0; i < previousTaskList.size(); i++) {
            //根据前置节点查找文件位置
            QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
            taskFileTypeQueryWrapper
                    .eq("activity_id", ((Task) previousTaskList.get(i)).getId())
                    .orderByDesc("create_time");
            TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
            String attachments = taskFileType.getAttachments();
            list.add(attachments);
        }
        String files = null;
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                if (list.get(i) != null) {
                    files += list.get(i).toString();
                }
            } else {
                if (list.get(i) != null) {
                    files += list.get(i).toString() + ",";
                }
            }
        }
        result.setResult(files);
        return result;
    }

    /**
     * @author: wangbin
     * @date:2020/8/18
     * @params: [dkey 流程定义的key]
     * @return:java.util.List<org.activiti.engine.impl.pvm.process.ActivityImpl>
     * @描述: 根据流程定义的key获取流程定义所有的activity
     * <p>
     * 释义：在设计流程时每一个组件在Activiti中都可以称之为——Activity，部署流程时引擎把XML文件保存到数据库；
     * 当启动流程、完成任务时会从数据库读取XML并转换为Java对象，如果想在处理任务时获取任务的一些配置，例如某个任务配置了哪些监听器或者条件Flow配置了什么条件表达式，可以获取具体的Activity。
     */
    //存放流程对应的所有activity
    private static Map<String, List<ActivityImpl>> processActivitiMap = new HashMap<>();

    public List<ActivityImpl> getAllActivities(String dkey) {
        List<ActivityImpl> activities = processActivitiMap.get(dkey);
        if (activities == null) {
            ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(dkey).singleResult();
            ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(definition.getId());

            //获取所有的activity
            activities = processDefinition.getActivities();
            processActivitiMap.put(dkey, activities);
        }

        return activities;
    }

    /**
     * @author: wangbin
     * @date:2017/5/10 9:32
     * @params:
     * @return:
     * @描述: 1.通过taskId获得executionid
     * 2.通过executionId获得currentActivityId
     * 3.通过currentActivityId获得ActivityImpl对象
     * 4.通过ActivityImpl对象获得incomingTransitions()
     * 5.通过transitionImpl对象获得source（ActivityImpl类型）
     * 6.通过ActivityImpl获得activityId
     * 7.通过activityId（这个activityId就是当前任务所在节点的前一个节点了）在流程历史里查询对应的task。
     */
    public List<String> getPrevActivitiByCurrentTaskId(String dkey, String currentTaskId) {
        List<String> preTaskIds = new ArrayList<>();
        TaskQuery taskQuery = taskService.createTaskQuery();
        ExecutionQuery executionQuery = runtimeService.createExecutionQuery();
        org.activiti.engine.task.Task task = taskQuery.taskId(currentTaskId).singleResult();
        if (task != null) {
            String executionId = task.getExecutionId();
            Execution execution = executionQuery.executionId(executionId).singleResult();
            String activityId = execution.getActivityId();
            List<ActivityImpl> allActivities = getAllActivities(dkey);
            for (ActivityImpl activity : allActivities) {
                String id = activity.getId();
                if (!id.equals(activityId)) {
                    continue;
                }
                List<PvmTransition> incomingTransitions = activity.getIncomingTransitions();
                for (PvmTransition transition : incomingTransitions) {
                    PvmActivity source = transition.getSource();
                    String preTaskId = source.getId();
                    preTaskIds.add(preTaskId);
                }
            }
        }
        return preTaskIds;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取上个任务节点
     * @Date: 2020/5/6
     * @params: [dkey 流程定义的key]
     * @Version: 1.0
     */


    public HistoricTaskInstance getPrevTaskByCurrentTaskId(String dkey, String processInstanceId, String taskId) {
        HistoricTaskInstance historicTaskInstance = null;
        List<String> prevTaskIds = getPrevActivitiByCurrentTaskId(dkey, taskId);
        if (prevTaskIds != null && prevTaskIds.size() > 0) {
            Map<String, HistoricActivityInstance> instanceMap = new HashMap<>();
            //遍历当前节点的所有incoming节点。判断最新的节点是哪个
            for (String preact : prevTaskIds) {
                HistoricActivityInstance activityInstance = historyService.createHistoricActivityInstanceQuery()
                        .processInstanceId(processInstanceId).activityId(preact).singleResult();
                if (activityInstance == null) {
                    continue;
                }
                Date endTime = activityInstance.getEndTime();
                HistoricActivityInstance activityInstance1 = instanceMap.get(taskId);
                if (activityInstance1 != null) {
                    Date endTime1 = activityInstance1.getEndTime();
                    if (endTime1.after(endTime)) {
                        continue;
                    }
                    instanceMap.put(taskId, activityInstance1);
                } else {
                    instanceMap.put(taskId, activityInstance);
                }

            }
            HistoricActivityInstance activityInstance = instanceMap.get(taskId);
            if (activityInstance != null) {
                String hisTaskId = activityInstance.getTaskId();
                historicTaskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).taskId(hisTaskId).singleResult();
            }
        }
        return historicTaskInstance;
    }

    //删除变量中最后一个节点
    public void backActivityIdLists(String ProcessInstanceId) {
        //获取任务执行过程节点,删除最后一个任务节点id
        String activityId = null;
        List activityIdLists = (List) runtimeService.getVariable(ProcessInstanceId, "activityIdLists");
        if (activityIdLists != null && activityIdLists.size() > 0) {
            activityIdLists.remove(activityIdLists.size() - 1);
        }
        runtimeService.setVariable(ProcessInstanceId, "activityIdLists", activityIdLists);
    }

    //完成在流程变量中插入任务id
    public void completeActivityIdLists(ProcessInstance instance) {
        List activityIdLists = (List) runtimeService.getVariable(instance.getId(), "activityIdLists");
        if (activityIdLists != null) {
            activityIdLists.add(instance.getActivityId());
        } else {
            activityIdLists = new ArrayList();
            activityIdLists.add(instance.getActivityId());
        }
        runtimeService.setVariable(instance.getId(), "activityIdLists", activityIdLists);
    }

    /**
     * 待办任务列表
     */
    @ResponseBody
    @GetMapping(value = "todoTasks")
    public Object todoTasks(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser user = CommonUtil.getUser();
//        List<IdentityLink> identityLinks = taskService
//                .getIdentityLinksForTask("2104");
//        for (IdentityLink identityLink : identityLinks) {
//            System.out.println(identityLink.getUserId());
//        }
        QueryWrapper<IdentitylinkUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<IdentitylinkUser> lists = identitylinkService.list(queryWrapper);
        Set<String> set = new HashSet();
        List processInfoList = new ArrayList();
        for (IdentitylinkUser user1 : lists) {
            if (user1.getProcInstId() != null) {
                set.add(user1.getProcInstId());
            }

        }
        for (String instId : set) {
            QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
            processInfoQueryWrapper
                    .eq("process_instance_id", instId);
            ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
            processInfo.setTaskStatus("进行中");
            processInfoList.add(processInfo);
        }
        QueryWrapper<ActHiTaskinst> hiqueryWrapper = new QueryWrapper<>();
        hiqueryWrapper.eq("ASSIGNEE_", user.getId());
        List<ActHiTaskinst> actHiTaskinsts = iActHiTaskinstService.list(hiqueryWrapper);
        Set<String> hiSet = new HashSet();
        String[] arr = set.toArray(new String[set.size()]);
        for (ActHiTaskinst user2 : actHiTaskinsts) {
            if (user2.getProcInstID() != null) {
                for(String str: arr){
                    if(str.equals(user2.getProcInstID())){
                        continue;
                    }else {
                        hiSet.add(user2.getProcInstID());
                    }
                }
            }
        }

        for (String instId : hiSet) {
            QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
            processInfoQueryWrapper
                    .eq("process_instance_id", instId);
            ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
            processInfo.setTaskStatus("已结束");
            processInfoList.add(processInfo);
        }


        Result result = new Result();
        result.setResult(new

                Page().

                setRecords(processInfoList).

                setTotal((long) processInfoList.

                        size()));
        return result;
//        List<org.activiti.engine.task.Task> tasks = taskService
//                .createTaskQuery()
//                .taskCandidateOrAssigned(user.getId())
//                .list();
//        List taskList = new ArrayList();
//        for (org.activiti.engine.task.Task task : tasks) {
//            QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
//            processInfoQueryWrapper
//                    .eq("process_definition_id", task.getProcessDefinitionId());
//            ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
//            taskList.add(processInfo);
//        }

    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取节点描述
     * @Date: 2020/5/6
     * @Version: 1.0
     */


    @GetMapping("loadDescription/{processId}")
    @ResponseBody
    public Result loadDescription(@PathVariable String processId) {
        LoginUser user = CommonUtil.getUser();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        System.out.println("看看数据：+++++++" + instance.getName() + instance.getDescription() + instance.getProcessDefinitionId());
        //获取节点描述
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", instance.getActivityId())
                .orderByDesc("create_time");

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
//        System.out.println("看看是什么：++"+taskFileType.getDescription());
        Result result = new Result();
        result.setResult(taskFileType.getDescription());
        return result;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取当前位置
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("loadUser/{processId}")
    @ResponseBody
    public Result loadUser(@PathVariable String processId) {
        LoginUser user = CommonUtil.getUser();
        System.out.println("看看user是多少：" + user.getId());
        QueryWrapper<IdentitylinkUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<IdentitylinkUser> lists = identitylinkService.list(queryWrapper);
        System.out.println("listsshishneme:" + lists);


        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //获取上传文件格式
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", instance.getActivityId())
                .orderByDesc("create_time");
        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);  //得到对应的activityId

        List<org.activiti.engine.task.Task> instid = null;
        try {
            instid = taskService.createTaskQuery().processInstanceId(taskFileType.getInstanceId()).orderByTaskCreateTime().desc().list();
        } catch (Exception e) {
            e.printStackTrace();
        }


        Result result = new Result();
        for (int i = 0; i < instid.size(); i++) {
            if (instid.get(i).getTaskDefinitionKey().equals(taskFileType.getActivityId())) {
                SysUser sysUser = sysUserService.getById(instid.get(i).getAssignee());
                System.out.println("我想看看user都有谁：+++" + instid.get(i).getAssignee());
                result.setResult(sysUser.getUsername());
                System.out.println("看看instid是什么数据：" + instid.get(i).getTaskDefinitionKey());
            }
        }

        /*     List processInfoList = new ArrayList();*/
/*        for (IdentitylinkUser user1 :lists){
            System.out.println("看一看id："+user.getId()+user1.getUserId());
            QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
            identitylinkUserQueryWrapper
                    .eq("proc_inst_id",instid.getProcessInstanceId());  //eq的作用是比较等于
            if(user.getId().equals(user1.getUserId())){   //首先判断procinstid（流程实例id）是否为空
                SysUser sysUser = sysUserService.getById(identityuser.getUserId());
                System.out.println("我想看看user都有谁：+++"+identityuser.getUserId());
                result.setResult(sysUser.getUsername());
            }
        }*/


        System.out.println("看一看result：++++" + result.getResult() + result.getOutFileType());
        return result;
    }


    /**
     * @Author: 风中的那朵云
     * @Description: 获取开始时间和结束时间
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("loadStart/{processId}")
    @ResponseBody
    public Result loadStart(@PathVariable String processId) {

        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //获取上传文件格式
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", instance.getActivityId())
                .orderByDesc("create_time");

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
//        System.out.println("看看是什么：++"+taskFileType.getStartTime()+taskFileType.getEndTime());
        Result result = new Result();
        result.setResult(taskFileType.getStartTime());
        return result;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取开始时间和结束时间
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("loadEnd/{processId}")
    @ResponseBody
    public Result loadEnd(@PathVariable String processId) {

        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //获取上传文件格式
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("definition_id", instance.getProcessDefinitionId())
                .eq("activity_id", instance.getActivityId())
                .orderByDesc("create_time");

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
//        System.out.println("看看是什么：++"+taskFileType.getStartTime()+taskFileType.getEndTime());
        Result result = new Result();
        result.setResult(taskFileType.getEndTime());
        return result;
    }

    /*    *//**
     * @Author: 风中的那朵云
     * @Description: 获取节点名称
     * @Date: 2020/5/6
     * @Version: 1.0
     *//*
    @GetMapping("loadName/{processId}")
    @ResponseBody
    public Result loadName(@PathVariable String processId) {

        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //获取上传文件格式
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper
                .eq("d", instance.getProcessDefinitionId())
                .eq("activity_id", instance.getActivityId())
                .orderByDesc("create_time");

        Task task = taskService.getOne(taskQueryWrapper);
        System.out.println("看看是什么：++"+taskFileType.getStartTime()+taskFileType.getEndTime());
        Result result = new Result();
        result.setResult(taskFileType.getStartTime());
        return result;
    }*/

    /**
     * 多步回退wb
     */
    public void rollback(TaskOpinion opinion) {
        // 当前任务Id
        String taskId = opinion.getTaskId();
        // 取得当前任务.当前任务节点
        HistoricTaskInstance currTask = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        // 取得流程定义
        ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(currTask.getProcessDefinitionId());
        // 取得本步活动
        ActivityImpl currActivity = ((ProcessDefinitionImpl) definition).findActivity(currTask.getTaskDefinitionKey());
        // 本节点入口
        List<PvmTransition> nextTransitionList = currActivity.getIncomingTransitions();
        // 本节点出口
        List<PvmTransition> pvmTransitionList = currActivity.getOutgoingTransitions();
        // 新建一个节点连线关系集合（存储原流程出口）
        List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
        for (PvmTransition pvmTransition : pvmTransitionList) {
            oriPvmTransitionList.add(pvmTransition);
        }
        // 清除当前活动的出口
        pvmTransitionList.clear();
        // 新建一个出口节点集合（存储新流程出口）
        List<TransitionImpl> newTransitions = new ArrayList<TransitionImpl>();
        // 循环本节点入口
        for (PvmTransition nextTransition : nextTransitionList) {
            PvmActivity nextActivity = nextTransition.getSource();
            //查找上一节点
            ActivityImpl nextActivityImpl = ((ProcessDefinitionImpl) definition).findActivity(nextActivity.getId());
            List<PvmTransition> nextTransitionListN = nextActivityImpl.getIncomingTransitions();

            String type = (String) nextActivityImpl.getProperty("type");
            if ("parallelGateway".equals(type)) {// 并行路线
                // 循环上一节点入口
                for (PvmTransition nextTransitionN : nextTransitionListN) {
                    PvmActivity nextActivityN = nextTransitionN.getSource();
                    //查找上上一节点
                    ActivityImpl nextNextActivityImpl = ((ProcessDefinitionImpl) definition).findActivity(nextActivityN.getId());
                    // 建立新出口
                    TransitionImpl newTransition = currActivity.createOutgoingTransition();
                    newTransition.setDestination(nextNextActivityImpl);
                    newTransitions.add(newTransition);
                }
            }

            taskService.complete(taskId);
            // 恢复方向
            for (TransitionImpl transitionImpl : newTransitions) {
                currActivity.getOutgoingTransitions().remove(transitionImpl);
            }
            for (PvmTransition pvmTransition : oriPvmTransitionList) {
                pvmTransitionList.add(pvmTransition);
            }
        }
    }

    //回退
    public void backTaskCmd(String taskId, Map variables, List backTaskIds) {
        CommandExecutor commandExecutor = ((ServiceImpl) taskService).getCommandExecutor();
        commandExecutor.execute(new BackTaskCmd(taskId, variables, backTaskIds));
    }


    /*----------------------------新增----------------------------------------*/

    /**
     * 我的任务列表
     */
    @ResponseBody
    @GetMapping(value = "myTasks")
    public Object myTasks(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser user = CommonUtil.getUser();
        System.out.println("看看user是多少：" + user.getId());
        QueryWrapper<IdentitylinkUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        List<IdentitylinkUser> lists = identitylinkService.list(queryWrapper);
        Set<String> set = new HashSet();
        List processInfoList = new ArrayList();
        for (IdentitylinkUser user1 : lists) {
            if (user1.getProcInstId() != null) {   //首先判断procinstid（流程实例id）是否为空
                set.add(user1.getProcInstId());
            }

        }
        for (String instId : set) {
            QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
            processInfoQueryWrapper
                    .eq("process_instance_id", instId);  //eq的作用是比较等于
            List<ProcessInfo> processList = processService.list(processInfoQueryWrapper);
            for (ProcessInfo process : processList) {
                if (process.getStatus() != ProcessInfo.status_submit) {
                    process.setTaskName("已结束");
                    continue;
                }
                ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(process.getProcessInstanceId()).singleResult();
                //保证运行ing
                if (instance == null) {
                    process.setTaskName("已结束");
                    continue;
                }
                TaskQuery query = this.taskService.createTaskQuery().processInstanceId(process.getProcessInstanceId());
                List<org.activiti.engine.task.Task> list = query.list();
                for (int i = 0; i < list.size(); i++) {
                    process.setTaskName(list.get(i).getName());
                }
                System.out.println("kankanknakankanaknak++++" + process.getTaskName());
                processInfoList.add(process);
            }
        }


        Result result = new Result();
        result.setResult(new Page().setRecords(processInfoList).setTotal((long) processInfoList.size()));
        return result;

    }

    /**
     * 所有节点信息表
     */
    @ResponseBody
    @GetMapping(value = "getFileTypes/{modelId}")
    public Result getFileTypes(@PathVariable String modelId) {
    /*    QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("model_id", processInfo.getModelId());
        List<TaskFileType> task=iTaskFileTypeService.list(taskFileTypeQueryWrapper);*/

        List<TaskFileType> taskFileTypes = iTaskFileTypeService.getByModelId(modelId);

        System.out.println("taskFileTypes:" + taskFileTypes.toString());
        QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
        processInfoQueryWrapper.eq("model_id", modelId);  //eq的作用是比较等于
        ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
        System.out.println("proooooo:" + processInfo.getProcessInstanceId());
        QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
        identitylinkUserQueryWrapper.eq("proc_inst_id", processInfo.getProcessInstanceId());
        List<IdentitylinkUser> identitylinkUsers = identitylinkService.list(identitylinkUserQueryWrapper);
        List<SysUser> sysUsers = new ArrayList<>();
        for (int i = 0; i < identitylinkUsers.size(); i++) {
            SysUser sysUser = sysUserService.getById(identitylinkUsers.get(i).getUserId());
            sysUsers.add(sysUser);
        }
        System.out.println("identitylinkUsers:" + identitylinkUsers.toString());
        Map<String, Object> data = new HashMap<>();
        data.put("taskFileTypes", taskFileTypes);
        data.put("identitylinkUsers", identitylinkUsers);
        data.put("sysUsers", sysUsers);
        data.put("processInfo", processInfo);
        Result result = new Result();
        result.setResult(data);
        return result;
    }


    /**
     * @Author: 风中的那朵云
     * @Description: 获取当前位置名称
     * @Date: 2020/5/6
     * @Version: 1.0
     */


    @GetMapping("loadName/{processId}")
    @ResponseBody
    public Result loadName(@PathVariable String processId) {
        LoginUser user = CommonUtil.getUser();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        System.out.println("看看数据：+++++++" + instance.getName() + instance.getDescription() + instance.getProcessDefinitionId());
        //获取节点描述
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("activity_id", instance.getActivityId());

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
        System.out.println("看看是什么：++" + taskFileType.getName());
        Result result = new Result();
        result.setResult(taskFileType.getName());
        return result;
    }


    /**
     * @Author: 风中的那朵云
     * @Description: 获取前一节点的执行人员
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @GetMapping("getPreUser/{processId}")
    @ResponseBody
    public Result getPreUser(@PathVariable String processId) {
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
//        //上一个节点
//        List<HistoricTaskInstance> list = historyService
//                .createHistoricTaskInstanceQuery()
//                .processInstanceId(processId)
//                .orderByHistoricTaskInstanceEndTime()
//                .desc()
//                .list();
//        HistoricTaskInstance taskInstance = null;
//        if (!list.isEmpty()) {
//            if (list.get(0).getEndTime() != null) {
//                taskInstance = list.get(0);
//            }
//        }
//
        Result result = new Result();
        String activityId = null;
        List activityIdLists = (List) runtimeService.getVariable(instance.getId(), "activityIdLists");
        if (activityIdLists != null && activityIdLists.size() > 0) {
            activityId = (String) activityIdLists.get(activityIdLists.size() - 1);
        }
        if (activityId == null) {
            return result;
        }
        //根据前置节点查找文件位置
        QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
        identitylinkUserQueryWrapper
                .eq("activity_id", activityId);
        IdentitylinkUser identitylinkUser = identitylinkService.getOne(identitylinkUserQueryWrapper);
        SysUser userName = sysUserService.getById(identitylinkUser.getUserId());
        System.out.println("这个用户是谁：+++" + userName.getUsername());
        if (userName.getUsername() != null) {
            result.setResult(userName.getUsername());
        }
        return result;
    }

    @GetMapping("getMyUser/{processId}")
    @ResponseBody
    public Result getMyUser(@PathVariable String processId) {
        LoginUser user = CommonUtil.getUser();
        QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
        processInfoQueryWrapper
                .eq("process_instance_id", processId);  //eq的作用是比较等于
        ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
        System.out.println("processInfo.toString():" + processInfo.toString());

  /*      ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        System.out.println("看看数据：+++++++" + instance.getName() + instance.getDescription() + instance.getProcessDefinitionId());*/
        //获取节点描述
        QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
        identitylinkUserQueryWrapper
                .eq("proc_inst_id", processInfo.getProcessInstanceId())
                .eq("user_id", user.getId());

        IdentitylinkUser identitylinkUser = identitylinkService.getOne(identitylinkUserQueryWrapper);
        System.out.println("identitylinkUser.toString():" + identitylinkUser.toString());
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("activity_id", identitylinkUser.getActivityId());

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);

        System.out.println("看看是什么：++" + taskFileType.getName());
        Result result = new Result();
        result.setResult(taskFileType.getName());
        return result;
    }

    /*
     * @Description: 获取执行天数
     * */
    @GetMapping("loadDateDiff/{processId}")
    @ResponseBody
    public Result loadDateDiff(@PathVariable String processId) {
        LoginUser user = CommonUtil.getUser();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        System.out.println("看看数据：+++++++" + instance.getName() + instance.getDescription() + instance.getProcessDefinitionId());
        //获取节点描述
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("activity_id", instance.getActivityId());

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
        System.out.println("看看是什么：++" + taskFileType.getDescription());
        Result result = new Result();
        result.setResult(taskFileType.getDateDiff());
        return result;
    }

    /*
     * @Description: 获取时间状态是否超时
     * */
    @GetMapping("loadTimeStatus/{processId}")
    @ResponseBody
    public Result loadTimeStatus(@PathVariable String processId) throws ParseException {
        LoginUser user = CommonUtil.getUser();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        System.out.println("看看数据：+++++++" + instance.getName() + instance.getDescription() + instance.getProcessDefinitionId());
        //获取节点描述
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper
                .eq("activity_id", instance.getActivityId());

        TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
        /*        System.out.println("看看最终时间什么：++" + taskFileType.getEndTime());*/

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");    //格式化规则
        Date date = new Date();
        String momentTime = simpleDateFormat.format(date);
 /*       Date end=taskFileType.getEndTime();
        String endTimes=simpleDateFormat.format(end);*/


        System.out.println("查看当前时间是几点：" + momentTime);
        System.out.println("查看最终时间时间是几点：" + taskFileType.getEndTime().getTime());
        if (taskFileType.getEndTime().after(simpleDateFormat.parse(momentTime))) {
            taskFileType.setTimeStatus(0);
        } else {
            taskFileType.setTimeStatus(1);
        }

        Result result = new Result();
        result.setResult(taskFileType.getTimeStatus());
        return result;
    }

    /**
     * 所有节点信息表
     */
    @ResponseBody
    @GetMapping(value = "mygetFileTypes/{modelId}")
    public Result mygetFileTypes(@PathVariable String modelId) {
        LoginUser user = CommonUtil.getUser();
        QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
        processInfoQueryWrapper.eq("model_id", modelId);
        ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
        QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
        identitylinkUserQueryWrapper
                .eq("proc_inst_id", processInfo.getProcessInstanceId())
                .eq("user_id", user.getId());
        List<IdentitylinkUser> identitylinkUsers = identitylinkService.list(identitylinkUserQueryWrapper);
        System.out.println("identitylinkUsers:" + identitylinkUsers.toString());
        List<SysUser> sysUsers = new ArrayList<>();
        for (int i = 0; i < identitylinkUsers.size(); i++) {
            SysUser sysUser = sysUserService.getById(identitylinkUsers.get(i).getUserId());
            sysUsers.add(sysUser);

        }
        List<TaskFileType> taskFileTypes = iTaskFileTypeService.getByModelId(modelId);
        Map<String, Object> data = new HashMap<>();
        data.put("taskFileTypes", taskFileTypes);
        data.put("identitylinkUsers", identitylinkUsers);
        data.put("sysUsers", sysUsers);
        data.put("processInfo", processInfo);
        Result result = new Result();
        result.setResult(data);
        return result;
    }

    /**
     * @Author: 风中的那朵云
     * @Description: 获取流程信息
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @ResponseBody
    @GetMapping(value = "getFlowDetails/{modelId}")
    public Result getFlowDetails(@PathVariable String modelId) {
        QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
        processInfoQueryWrapper.eq("model_id", modelId);
        ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);
        QueryWrapper<ActHiTaskinst> actHiTaskinstQueryWrapper = new QueryWrapper<>();
        actHiTaskinstQueryWrapper.eq("PROC_INST_ID_", processInfo.getProcessInstanceId());
        List<ActHiTaskinst> actHiTaskinstList = iActHiTaskinstService.list(actHiTaskinstQueryWrapper);
        for (int i = 0; i < actHiTaskinstList.size(); i++) {

        }
        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();
        taskFileTypeQueryWrapper.eq("model_id", modelId);
        List<TaskFileType> taskFileTypeList = iTaskFileTypeService.list(taskFileTypeQueryWrapper);
        List<FlowTaskDetails> FlowTaskDetails = new ArrayList();
        for (int i = 0; i < taskFileTypeList.size(); i++) {
            FlowTaskDetails flowTaskDetails = new FlowTaskDetails();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            flowTaskDetails.setTheStartTime(sdf.format(taskFileTypeList.get(i).getStartTime()));
            flowTaskDetails.setTheEndTime(sdf.format(taskFileTypeList.get(i).getEndTime()));
            flowTaskDetails.setDescription(taskFileTypeList.get(i).getDescription());
            flowTaskDetails.setAttachments(taskFileTypeList.get(i).getAttachments());
            flowTaskDetails.setNodeName(taskFileTypeList.get(i).getTaskName());
            flowTaskDetails.setAttachmentsName(taskFileTypeList.get(i).getAttachmentsName());
            for (int y = 0; y < actHiTaskinstList.size(); y++) {
                if (taskFileTypeList.get(i).getActivityId().equals(actHiTaskinstList.get(y).getTaskDefKey())) {
                    if (actHiTaskinstList.get(y).getStartTime() != null) {
                        flowTaskDetails.setRelStartTime(actHiTaskinstList.get(y).getStartTime().substring(0, 10));
                    }
                    if (actHiTaskinstList.get(y).getEndTime() != null) {
                        flowTaskDetails.setRelEndTime(actHiTaskinstList.get(y).getEndTime().substring(0, 10));
                    }
//                    if(actHiTaskinstList.get(y).getName() !=null){
//                        flowTaskDetails.setNodeName(actHiTaskinstList.get(y).getName());
//                    }
                }
            }
            FlowTaskDetails.add(flowTaskDetails);
        }
        Result result = new Result();
        result.setResult(FlowTaskDetails);
        return result;
    }
}
